﻿using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Data;
using System.Text;
using DB;

public class JsonConvertor
{
    #region dataTable转换成Json格式
    /// <summary>      
    /// dataTable转换成Json格式      
    /// </summary>      
    /// <param name="dt"></param>      
    /// <returns></returns>      
    public static string ToJson(DataTable dt)
    {

        StringBuilder jsonBuilder = new StringBuilder();
        if (dt.Rows.Count == 0)
        {
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName.ToString());
            jsonBuilder.Append("\":[]}");
            return jsonBuilder.ToString();
        }
        jsonBuilder.Append("{\"");
        jsonBuilder.Append(dt.TableName.ToString());
        jsonBuilder.Append("\":[");

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }

    #endregion dataTable转换成Json格式

    #region DataSet转换成Json格式
    /// <summary>      
    /// DataSet转换成Json格式      
    /// </summary>      
    /// <param name="ds">DataSet</param>      
    /// <returns></returns>      
    public static string ToJson(DataSet ds)
    {
        StringBuilder json = new StringBuilder();

        foreach (DataTable dt in ds.Tables)
        {
            json.Append("{\"");
            json.Append(dt.TableName);
            json.Append("\":");
            json.Append(ToJson(dt));
            json.Append("}");
        }
        return json.ToString();
    }
    #endregion


    public static string getJsonTable(String str_sql)
    {
        DataAccess da = new DataAccess();
        DataTable dt = da.GetTable(str_sql);
        return JsonConvertor.ToJson(dt);
    }
}
